# encoding: utf-8
"""
@Time   : 2018/12/28 16:26
@Author : XJH
"""

"""
实例37：卷积函数的使用
"""
# # 1. 定义输入变量
# import tensorflow as tf
# input = tf.Variable(tf.constant(1.0, shape=[1, 5, 5, 1]))
# input2 = tf.Variable(tf.constant(1.0, shape=[1, 5, 5, 2]))
# input3 = tf.Variable(tf.constant(1.0, shape=[1, 4, 4, 1]))
# # 2. 定义卷积核变量
# filter1 = tf.Variable(tf.constant([-1.0, 0, 0, -1], shape=[2, 2, 1, 1]))
# # 3. 定义卷积操作
# op1 = tf.nn.conv2d(input, filter1, strides=[1, 2, 2, 1], padding='SAME')
# # 4. 运行卷积操作
# init = tf.global_variables_initializer()
# with tf.Session() as sess:
#     sess.run(init)
#     print(op1.shape)
#     print("op1: \n", sess.run(op1))

"""
实例38：使用卷积提取图片的轮廓
"""
# 1. 载入图片并显示
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import tensorflow as tf

myimg = mpimg.imread('img.jpg')
plt.imshow(myimg)
plt.axis('off')
plt.show()
print(myimg.shape)
# 2. 定义占位符、卷积核、卷积op
full = np.reshape(myimg, [1, 3024, 4032, 3])
inputfull = tf.placeholder(dtype=tf.float32, shape=[1, 3024, 4032, 3])
filter = tf.Variable(tf.constant(
    [[-1.0, -1.0, -1.0],
     [0, 0, 0],
     [1.0, 1.0, 1.0],
     [-2.0, -2.0, -2.0],
     [0, 0, 0],
     [2.0, 2.0, 2.0],
     [-1.0, -1.0, -1.0],
     [0, 0, 0],
     [1.0, 1.0, 1.0]],
    shape=[3, 3, 3, 1]
))
op = tf.nn.conv2d(inputfull, filter, strides=[1, 1, 1, 1], padding='SAME')
o = tf.cast(
    (
        (op - tf.reduce_min(op)) / (tf.reduce_max(op) - tf.reduce_min(op)) * 255
    ), tf.uint8)
# 3. 运行卷积操作并显示
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    t, f = sess.run([o, filter], feed_dict={inputfull: full})
    print(t.shape)
    t = np.reshape(t, [3024, 4032])
    plt.imshow(t, cmap='gray_r')
    plt.axis('off')
    plt.show()